package com.jeeplus.modules.common.excel.common.validator.impl;

import com.jeeplus.common.utils.StringUtil;
import com.jeeplus.modules.api.changeReason.entity.XgChangeReasonRedis;
import com.jeeplus.modules.api.changeReason.service.XgChangeReasonService;
import com.jeeplus.modules.common.excel.common.anno.IsChangeReasonType;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.utils.SpringBeanUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wang.yishu
 * @version 1.0
 * @className ChangeReasonTypeValidator
 * @description TODO
 * @date 2022/7/19 8:24
 */
public class IsChangeReasonTypeValidator extends AbstractValidator {
    private IsChangeReasonType isChangeReasonType;

    private static final String KEY = "changeReasonType";

    @Override
    public boolean canValidate(Field field) {
        isChangeReasonType = field.getDeclaredAnnotation(IsChangeReasonType.class);
        return isChangeReasonType != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        XgChangeReasonService xgChangeReasonService = SpringBeanUtils.getBean(XgChangeReasonService.class);
        List<XgChangeReasonRedis> usingChangeReasonList = xgChangeReasonService.findUsingChangeReasonList(null, false);
        field.setAccessible(true);
        Object value = null;
        try {
            value = field.get(entity);
            if (value == null) return null;
            if (value instanceof String) {
                String valueStr = value.toString();
                List<Object> collect = usingChangeReasonList.stream().filter(xgChangeReasonRedis -> ((XgChangeReasonRedis) xgChangeReasonRedis).getName().equals(valueStr)).collect(Collectors.toList());
                if (collect.size() == 0) {
                    return this.isChangeReasonType.msg();
                }
                XgChangeReasonRedis v = (XgChangeReasonRedis) collect.get(0);
                String transformTo = this.isChangeReasonType.transformTo();
                if (StringUtil.isNotBlank(transformTo)) {
                    Field transformToField = entity.getClass().getDeclaredField(transformTo);
                    transformToField.setAccessible(true);
                    if (transformToField.getType().getName().equals(String.class.getName())) {
                        transformToField.set(entity, v.getId().toString());
                    } else if (transformToField.getType().getName().equals(Integer.class.getName())) {
                        transformToField.set(entity, Integer.valueOf(v.getId().toString()));
                    }
                }
            } else {
                return "异动原因类型名称数据类型错误！";
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }
}
